package org.tao.lightningmq.nameserver.store;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author lht
 * @date 2025/1/17 - 12:45
 * @description:
 */
public class ReplicationChannelManager {

    private static Map<String, ChannelHandlerContext> contextMap = new ConcurrentHashMap<>();

    public static Map<String, ChannelHandlerContext> getContextMap() {
        return contextMap;
    }

    public Map<String, ChannelHandlerContext> getValidSlaveChannelMap() {
        //contextMap.entrySet().removeIf(entry -> !entry.getValue().channel().isActive());// 并发问题，不能这么用
        List<String> inValidChannelReqIdList = new ArrayList<>();
        //判断当前采用的同步模式是哪种方式
        for (String reqId : contextMap.keySet()) {
            Channel slaveChannel = contextMap.get(reqId).channel();
            if (!slaveChannel.isActive()) {
                inValidChannelReqIdList.add(reqId);
            }
        }
        if (!inValidChannelReqIdList.isEmpty()) {
            for (String reqId : inValidChannelReqIdList) {
                //移除不可用的channel
                contextMap.remove(reqId);
            }
        }
        return contextMap;
    }

    public void put(String key, ChannelHandlerContext context) {
        contextMap.put(key, context);
    }

}
